package com.googlecode.jlogindexer.utils;

import java.io.IOException;
import java.net.MalformedURLException;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;

import com.googlecode.jlogindexer.document.LogDocument;

public class SolrUtils {
	
	private String solrUrl;
	private CommonsHttpSolrServer solrServer=null;
	private int docCount=0;
	
	
	private SolrUtils() {
		//TODO Initiate local server otherwise
	}
	
	public SolrUtils(String solrUrl){
		this.solrUrl=solrUrl;
		initServer();
	}
	

	public void initServer() {
		try {
		    System.out.println("SOLR URL::::"+solrUrl);
			solrServer =new CommonsHttpSolrServer(solrUrl);
		} catch (MalformedURLException e) {
			System.err.println("Unable to resolve Solr Url"+e.getMessage());
		}
			
	}


	public void addDocumentToSolr(LogDocument logDocument) {
		try {
			System.out.println("Adding logDocument bean: "+logDocument.getOutMessage());
			System.out.println("Solr server : "+solrServer);
			solrServer.addBean(logDocument);
			docCount++;
			System.out.println("COMMITTING TO SOLR >>>>>>>>>>>>>>>>>>>>>>");
			solrServer.commit();
			/*if (docCount%2==0){ //FIXME consider performance and usage. for now, commiting at all times
				System.out.println("10th document. commiting");
				solrServer.commit();
				System.gc();
			}*/
		} catch (SolrServerException e) {
			System.err.println("Could not add document to Solr Server. Possibly Down?"+e.getMessage());
		} 
		catch (IOException e) {
			System.err.println("Could not add document to Solr Server. Possibly Down?"+e.getMessage());
		}
	}
	
	
	
}